package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.client.article.IArticleClient;
import com.heima.client.wemedia.IWemediaClient;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserAuthenticationDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApAuthor;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.model.common.pojos.user.UserRealName;
import com.heima.model.common.pojos.wemedia.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.UserAuthenticationMapper;
import com.heima.user.service.UserAuthenticationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author: fly
 * @date: 2024-08-01 10:24
 */
@Service
public class UserAuthenticationServiceImpl extends ServiceImpl<UserAuthenticationMapper, UserRealName> implements UserAuthenticationService {
    @Autowired
    private UserAuthenticationMapper userAuthenticationMapper;
    @Autowired
    private ApUserMapper userMapper;
    @Autowired
    private IWemediaClient WemediaClient;

    @Autowired
    private IArticleClient articleClient;

    /**
     * 分页条件查询认证列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pageList(UserAuthenticationDto dto) {
        if (dto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //校验分页参数
        dto.checkParam();
        Page<UserRealName> page = new Page<>(dto.getPage(), dto.getSize());
        userAuthenticationMapper.selectPage(page, Wrappers.lambdaQuery(UserRealName.class)
                .eq(dto.getStatus() != null, UserRealName::getStatus, dto.getStatus())
                .orderByAsc(UserRealName::getCreatedTime));
        PageResponseResult pageResponseResult = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    /**
     * 审核通过
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult authPass(UserAuthenticationDto dto) {
        //修改ap_user_realname表中status
        UserRealName userRealName = UserRealName.builder()
                .userId(dto.getId())
                .status(UserRealName.Status.SUCCESS.getCode()).build();
        userAuthenticationMapper.update(userRealName, Wrappers.lambdaUpdate(UserRealName.class)
                .eq(UserRealName::getUserId, userRealName.getUserId()));
        //修改ap_user表中is_identity_authentication
        ApUser apUser = new ApUser();
        apUser.setId(dto.getId());
        apUser.setIsIdentityAuthentication((short) 1);
        userMapper.updateById(apUser);
        //准备参数
        ApUser user = userMapper.selectById(apUser.getId());
        WmUser wmUser = new WmUser();
        BeanUtils.copyProperties(user, wmUser, "id");
        wmUser.setApUserId(user.getId());
        //远程调用article微服务，获取author对象
        ResponseResult result = articleClient.getOne(user.getId());
        if (result.getCode() ==200 ){
            ApAuthor apAuthor = JSON.parseObject(JSON.toJSONString(result.getData()), ApAuthor.class);
            wmUser.setApAuthorId(apAuthor.getId());
            wmUser.setStatus((short) 9);
            wmUser.setCreatedTime(new Date());
            //远程调用wemedia微服务，创建自媒体账号，账号密码与app端一致
            ResponseResult res = WemediaClient.createWmUser(wmUser);
            if (res.getCode() == 200) {
                //修改ap_author中wm_user_id字段
                int data = (int) res.getData();
                apAuthor.setWmUserId(data);
                //远程调用article微服务，更新author
                articleClient.update(apAuthor);
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 拒绝
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(UserAuthenticationDto dto) {
        UserRealName userRealName = UserRealName.builder()
                .userId(dto.getId())
                .reason(dto.getMsg())
                .status(UserRealName.Status.FAIL.getCode()).build();
        userAuthenticationMapper.update(userRealName, Wrappers.lambdaUpdate(UserRealName.class)
                .eq(UserRealName::getUserId, userRealName.getUserId()));
        return PageResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
